// 整合脚本 - 处理PDF文件并执行多个操作（可自定义线宽）
// 禁用UI警告
app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;

// ====== 用户可配置参数 ======
var strokeWidth = 1.3; // 默认线宽 (pt)
var exportType = "svg"; // 默认导出格式: svg 或 png

// ========== 001Draw.jsx 功能 ==========
function createLine(doc, params) {
    try {
        var newPath = doc.pathItems.add();
        
        // 计算终点坐标
        var angleRad = params.angle * Math.PI / 180;
        var endX = params.startX + params.length * Math.cos(angleRad);
        var endY = params.startY + params.length * Math.sin(angleRad);
        
        // 添加路径点 (mm转pt: 1mm ≈ 2.834645669pt)
        var pt1 = newPath.pathPoints.add();
        var pt2 = newPath.pathPoints.add();
        
        pt1.anchor = [params.startX * 2.834645669, params.startY * 2.834645669];
        pt1.leftDirection = pt1.anchor;
        pt1.rightDirection = pt1.anchor;
        
        pt2.anchor = [endX * 2.834645669, endY * 2.834645669];
        pt2.leftDirection = pt2.anchor;
        pt2.rightDirection = pt2.anchor;
        
        // 设置线条属性
        newPath.stroked = true;
        newPath.strokeWidth = params.width;
        newPath.strokeColor = getColor(params.color);
        newPath.filled = false;
        
        // 设置为直线
        newPath.pathPoints[0].pointType = PointType.CORNER;
        newPath.pathPoints[1].pointType = PointType.CORNER;
        
        return newPath;
    } catch(e) {
        return null;
    }
}

function getColor(colorName) {
    var color = new RGBColor();
    switch(colorName.toLowerCase()) {
        case "black": color.red=0; color.green=0; color.blue=0; break;
        case "red": color.red=255; color.green=0; color.blue=0; break;
        case "blue": color.red=0; color.green=0; color.blue=255; break;
        default: color.red=0; color.green=0; color.blue=0;
    }
    return color;
}

// ========== 002DoMenu.jsx 功能 ==========
function selectSameStroke() {
    try {
        app.executeMenuCommand("Find Stroke Weight menu item");
        return true;
    } catch(e) {
        return false;
    }
}

// ========== 003AddArtboard.jsx 功能 ==========
function createArtboardsFromSelection(doc, margin) {
    var created = 0;
    var marginPt = margin * 2.834645669;
    
    for (var i = 0; i < doc.selection.length; i++) {
        var item = doc.selection[i];
        try {
            if (item.typename == "PathItem" && item.closed) {
                var bounds = item.geometricBounds;
                if (bounds && bounds.length == 4) {
                    var left = bounds[0] - marginPt;
                    var top = bounds[1] + marginPt;
                    var right = bounds[2] + marginPt;
                    var bottom = bounds[3] - marginPt;
                    
                    if (left < right && bottom < top) {
                        doc.artboards.add([left, top, right, bottom]);
                        created++;
                    }
                }
            }
        } catch(e) { /* 跳过错误项 */ }
    }
    return created;
}

// ========== 004DeleteFirstArtboard.jsx 功能 ==========
function deleteFirstArtboard(doc) {
    try {
        if (doc.artboards.length > 1) {
            doc.artboards[0].remove();
            return true;
        }
    } catch(e) { /* 处理错误 */ }
    return false;
}

// ========== 主处理函数 ==========
function processPDF(file, exportFormat) {
    var doc = app.open(file);
    var redrawState = app.redraw;
    app.redraw = false; // 禁用重绘提升性能
    
    try {
        // 0. 全选并释放剪切蒙版
        try {
            app.executeMenuCommand("selectall");
            app.executeMenuCommand("releaseMask");
            app.executeMenuCommand("deselectall"); // 取消所有选择
        } catch(e) {
            // 忽略错误继续执行
        }
        
        // 1. 绘制直线
        var lineParams = {
            startX: 0,   // 起点X (mm)
            startY: 0,   // 起点Y (mm)
            length: 100,  // 长度 (mm)
            angle: 180,    // 角度 (度)
            width: strokeWidth,   // 使用全局线宽变量 (pt)
            color: "Black"
        };
        var newLine = createLine(doc, lineParams);
        
        // 2. 选择相同粗细的路径
        if (newLine) {
            newLine.selected = true;
            selectSameStroke();
        }
        
        // 3. 在选中路径内创建画板 (0mm边距)
        var artboardsCreated = createArtboardsFromSelection(doc, 0);
        
        // 如果没有新增画板，则跳过后续操作
        if (artboardsCreated === 0) {
            return -2; // 特殊状态码：跳过文件
        }
        
        // 4. 删除原始画板
        if (artboardsCreated > 0) {
            deleteFirstArtboard(doc);
        }
        
        // 5. 重新执行001和002功能：绘制直线并选择相同粗细路径
        var newLine2 = createLine(doc, lineParams);
        if (newLine2) {
            newLine2.selected = true;
            selectSameStroke();
            
            // 删除所有选中的路径（包括新绘制的直线）
            deleteSelectedPaths(doc);
        }
        
        // 6. 保存文档 (PDF转AI)
        var saveFile = new File(file.fsName.replace(".pdf", ".ai"));
        var saveOptions = new IllustratorSaveOptions();
        saveOptions.pdfCompatible = true;
        doc.saveAs(saveFile, saveOptions);
        
        // 7. 根据选择的格式导出
        if (exportFormat === "png") {
            exportAsPNG(file, doc);
        } else {
            exportAsSVG(file, doc);
        }
        
        return artboardsCreated;
    } catch(e) {
        return -1; // 错误标志
    } finally {
        // 恢复重绘状态并关闭文档
        app.redraw = redrawState;
        doc.close(SaveOptions.DONOTSAVECHANGES);
    }
}

// ========== 批量处理 ==========
function processFolder() {
    // 获取用户自定义线宽
    var input = prompt("请输入线宽 (pt)", "1.3");
    if (input === null) return; // 用户取消
    
    strokeWidth = parseFloat(input);
    if (isNaN(strokeWidth) || strokeWidth <= 0) {
        alert("无效的线宽值，使用默认值 1.3pt");
        strokeWidth = 1.3;
    }
    
    // 选择导出格式
    var formatChoice = prompt("选择导出格式 (输入 1 或 2):\n1. SVG\n2. PNG", "1");
    if (formatChoice === null) return; // 用户取消
    
    if (formatChoice === "2") {
        exportType = "png";
    } else {
        exportType = "svg"; // 默认SVG
    }
    
    var folder = Folder.selectDialog("选择包含PDF的文件夹");
    if (!folder) return;
    
    var files = folder.getFiles("*.pdf");
    var totalProcessed = 0;
    var totalSkipped = 0;
    
    for (var i = 0; i < files.length; i++) {
        var result = processPDF(files[i], exportType);
        if (result > 0) {
            totalProcessed++;
        } else if (result === -2) {
            totalSkipped++;
        }
    }
    
    alert("处理完成！\n成功处理: " + totalProcessed + "个文件\n跳过: " + totalSkipped + "个文件\n使用线宽: " + strokeWidth + "pt");
}

// ========== 删除选中路径 ==========
function deleteSelectedPaths(doc) {
    try {
        // 从后往前删除避免索引问题
        for (var i = doc.selection.length - 1; i >= 0; i--) {
            var item = doc.selection[i];
            if (item.typename === "PathItem" || item.typename === "CompoundPathItem") {
                item.remove();
            }
        }
        return true;
    } catch(e) {
        return false;
    }
}

// ========== PNG导出功能 ==========
function exportAsPNG(file, doc) {
    // 临时保存原始交互级别
    var oldInteractionLevel = app.userInteractionLevel;
    app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;
    
    var exportOptions = new ExportOptionsPNG24();
    exportOptions.antiAliasing = true; // 抗锯齿
    exportOptions.transparency = true; // 透明背景
    exportOptions.resolution = 300; // 300 DPI
    exportOptions.artBoardClipping = true; // 按画板裁剪
    exportOptions.verticalScale = 500.0;
    exportOptions.horizontalScale = 500.0;
    
    var baseName = decodeURI(file.name).replace(/\.[^\.]+$/, "");
    var exportFolder = new Folder(file.parent + "/output/");
    if (!exportFolder.exists) exportFolder.create();

    // 创建输出目录
    var pngFolder = new Folder(exportFolder.fsName + "/PNG/");
    if (!pngFolder.exists) pngFolder.create();
    
    // 导出所有画板
    for (var i = 0; i < doc.artboards.length; i++) {
        doc.artboards.setActiveArtboardIndex(i);
        var artboardName = doc.artboards[i].name || "artboard_" + (i+1);
        var exportFile = new File(pngFolder.fsName + "/" + baseName + "_" + artboardName + ".png");
        doc.exportFile(exportFile, ExportType.PNG24, exportOptions);
    }
    
    // 恢复原始交互级别
    app.userInteractionLevel = oldInteractionLevel;
}

// ========== 优化的SVG导出功能 ==========
function exportAsSVG(file, doc) {
    // 临时保存原始交互级别
    var oldInteractionLevel = app.userInteractionLevel;
    app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS;
    
    var exportOptions = new ExportOptionsWebOptimizedSVG();
    exportOptions.compressed = false; // 不压缩SVG
    exportOptions.coordinatePrecision = 3; // 坐标精度
    exportOptions.cssProperties = SVGCSSPropertyLocation.PRESENTATIONATTRIBUTES;
    exportOptions.fontSubsetting = SVGFontSubsetting.None; // 不对子集字体
    exportOptions.fontType = SVGFontType.SVGFONT; // 保留字体为SVG字体
    exportOptions.svgResponsive = false; // 关闭响应式
    exportOptions.saveMultipleArtboards = true; // 支持多画板导出
    exportOptions.rasterImageLocation = RasterImageLocation.PRESERVE; // 保留原始位置
    
    var baseName = decodeURI(file.name).replace(/\.[^\.]+$/, "");
    var exportFolder = new Folder(file.parent + "/output/");
    if (!exportFolder.exists) exportFolder.create();

    var exportFile = new File(exportFolder.fsName + "/" + baseName + ".svg");
    doc.exportFile(exportFile, ExportType.WOSVG, exportOptions);
    
    // 恢复原始交互级别
    app.userInteractionLevel = oldInteractionLevel;
}

// 启动处理
processFolder();